//
//  HTMLStringViewController.swift
//  AutoPrint
//
//  Created by David on 16/10/7.
//  Copyright © 2016年 fatcat. All rights reserved.
//  在线预览webview

import UIKit

class HTMLStringViewController: UIViewController, NSURLSessionDataDelegate, UIWebViewDelegate {

    var filePath: String!
    var fileName: String!
    
    var navigationBar:UINavigationBar!
    
    var webVIew: UIWebView!
    var progressBar: UIProgressView!
    convenience init(path: String, name: String){
        self.init()
        filePath = path
        fileName = name
    }
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        webVIew = UIWebView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
        view.addSubview(webVIew)
        webVIew.delegate = self
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .Black
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        navigationBar.tintColor = UIColor.whiteColor()
        
        let navItem = UINavigationItem(title: fileName)
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(HTMLStringViewController.dismiss))
        
        navigationBar.pushNavigationItem(navItem, animated: true)
        
        progressBar = UIProgressView(frame: CGRect(x: 0, y: 64, width: view.bounds.width, height: 0))
        view.addSubview(progressBar)
        
        let resq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        resq.HTTPMethod = "POST"
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        resq.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        //filePath = ".\(filePath)"
        resq.HTTPBody = NSString(string: "act=filePreview&filePath=\(filePath)").dataUsingEncoding(NSUTF8StringEncoding)
        
//        self.webVIew.loadRequest(resq)
        self.webVIew.scalesPageToFit = true
        
        let sessionGetHTML = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue())
        NSURLSession.sharedSession().dataTaskWithRequest(resq) { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
            if err == nil {
                if let data = reData{
                    dispatch_async(dispatch_get_main_queue(), {
                        self.progressBar.setProgress(0.1, animated: true)
                        let urlStr = String(NSString(data: data, encoding: NSUTF8StringEncoding)!)
                        print(urlStr)
                        
                        let pvURL = NSURL(string: urlStr)
                        if pvURL != nil {
                            let newResq = NSURLRequest(URL: pvURL!)
                            
                            let getHTML = sessionGetHTML.dataTaskWithRequest(newResq) { (reData:NSData?, resp:NSURLResponse?, err:NSError?) in
                                if err == nil {
                                    if let data = reData {
                                        
                                        let htmlStr = String(NSString(data: data, encoding: NSUTF8StringEncoding)!)
                                        //print(htmlStr)
                                        dispatch_async(dispatch_get_main_queue(), {
                                            self.progressBar.setProgress(0.9, animated: true)
                                            self.webVIew.loadHTMLString(htmlStr, baseURL: NSURL(string: Fatcat.PREVIEW_BASE_URL)!)
                                            
                                        })
                                        
                                    }
                                }
                            }
                            getHTML.resume()
                            
                        }
                    })
                }
            }
        }.resume()
        
        
        
        
    }

    
    func webViewDidFinishLoad(webView: UIWebView) {
        self.progressBar.alpha = 0
    }
    
    func dismiss(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
